﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using GMAC.ReportingSystem.Business.Entities;
using System.Data;
using Entities = GMAC.ReportingSystem.Business.Entities;
using Components = GMAC.ReportingSystem.Business.Components;
using FrameworkManapro.Utilities;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class CallReasons : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();

        }

        #endregion

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.CallReasonComponent();
                var CallReason = ReadCallReason();
                CallReason.ID = frc.Create(CallReason);
                var audit = new FrameworkManapro.Audit.Audit<Entities.CallReason>
                {
                    EntityKey = CallReason.ID.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = CallReason,
                    UserId = ((Entities.User)Session["User"]).UserID
                };
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.CallReason>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Call Reason was successfully saved.", null);
                popupExtenderMessage.Show();
                this.PagingControl.TotalRecords = Search();
                Search();

                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New Call Reason", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Call Reason could not be saved", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            var frc = new Components.CallReasonComponent();
            try
            {
                var CallReason = ReadCallReason();
                if (hfID.Value.Trim() != string.Empty)
                {
                    CallReason.ID = int.Parse(hfID.Value);
                    var oldCallReason = frc.GetDetails(CallReason.ID);
                    frc.Edit(CallReason);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.CallReason>
                    {
                        EntityKey = CallReason.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldCallReason,
                        NewObject = CallReason,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.CallReason>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The CallReason was successfully saved.", null);
                    popupExtenderMessage.Show();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save CallReason", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The CallReason couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (grvCallReasons != null)
            {
                if (grvCallReasons.SelectedDataKey != null)
                {
                    try
                    {
                        var CallReasonId = (int)this.grvCallReasons.SelectedDataKey.Value;
                        var frc = new Components.CallReasonComponent();
                        var CallReason = frc.GetDetails(CallReasonId);
                        hfID.Value = CallReasonId.ToString();
                        txtDescription.Text = CallReason.Description;
                        ddlProductType.SelectedValue = ((int)CallReason.AccounTypeID).ToString();
                        optOptions.SelectedValue = CallReason.Status.ToString();
                        btnSave.Visible = true;
                        btnNew.Visible = false;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify Call Reason", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the CallReason.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A Call Reason must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvCallReasons.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A Call Reason must be selected.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.CallReasonComponent();
                if (grvCallReasons.SelectedDataKey != null)
                {
                    var CallReasonId = (int)this.grvCallReasons.SelectedDataKey.Value;
                    var CallReason = new Entities.CallReason { ID = CallReasonId };
                    var oldCallReason = frc.GetDetails(CallReason.ID);
                    frc.Delete(CallReason);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.CallReason>
                    {
                        EntityKey = CallReason.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldCallReason,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.CallReason>(audit);
                    auditDAC.InsertAudit();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Call Reason was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete Call Reason", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Call Reason couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            }
            ClearFields();
        }

        #endregion

        #region Other Events

        protected void grvCallReasons_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvCallReasons, "Select$" + e.Row.RowIndex);
                if (bool.Parse((e.Row.FindControl("hfStatus") as HiddenField).Value) == true)
                {
                    e.Row.Cells[2].Text = "Active";
                }
                else
                {
                    e.Row.Cells[2].Text = "Inactive";
                }
                int hdProductTypeId = int.Parse((e.Row.FindControl("hdProductTypeId") as HiddenField).Value);
                var cp = new Components.ProductComponent();
                var Product = new Product();
                Product = cp.Get(hdProductTypeId);
                e.Row.Cells[1].Text = Product.Description;
            }
        }

        #endregion

        #region Private Methods

        private void ClearFields()
        {
            txtDescription.Text = string.Empty;
            ddlProductType.SelectedValue = string.Empty;
            hfID.Value = string.Empty;
            optOptions.SelectedValue = "True";

            txtDescriptionSeach.Text = string.Empty;
            ddlProductTypeSearch.SelectedValue = string.Empty;
        }
        private void Initialize()
        {
            try
            {
                var bcProduct = new Components.ProductComponent();
                ddlProductType.DataSource = bcProduct.GetList();
                ddlProductType.DataTextField = "Description";
                ddlProductType.DataValueField = "AccountTypeID";
                ddlProductType.DataBind();
                ddlProductType.Items.Insert(0, new ListItem("Select...", string.Empty));

                ddlProductTypeSearch.DataSource = bcProduct.GetList();
                ddlProductTypeSearch.DataTextField = "Description";
                ddlProductTypeSearch.DataValueField = "AccountTypeID";
                ddlProductTypeSearch.DataBind();
                ddlProductTypeSearch.Items.Insert(0, new ListItem("Select...", string.Empty));

                optOptions.SelectedValue = "True";
                btnSave.Visible = false;
                btnNew.Visible = true;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected Call Reason?", null);
                this.PagingControl.TotalRecords = Search();
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }
        private void ValidateSecurity()
        {
            var beEntities = ((User)Session["User"]).Role.Security.GetEntitySecurity("CallReasons");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
               grvCallReasons.Visible = false;
                btnModify.Visible = false;
                btnDelete.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible = false;
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }
        private int Search()
        {
            try
            {
                var bc = new Components.CallReasonComponent();


                string Description = txtDescriptionSeach.Text;
                int? ProductType = null;
                if (!string.IsNullOrEmpty(ddlProductTypeSearch.SelectedValue))
                    ProductType = Convert.ToInt32(ddlProductTypeSearch.SelectedValue);
               

                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                paging.PageNumber = this.PagingControl.PageNumber;
                paging.PageSize = this.PagingControl.PageSize;
                paging.SortBy = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;



                Entities.CallReasonCollection CallReasoncollection = bc.Search(Description, ProductType, paging);

                grvCallReasons.DataSource = CallReasoncollection;
                grvCallReasons.DataBind();
                return CallReasoncollection.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Call Reason", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return 0;

            }
        }
        private Entities.CallReason ReadCallReason()
        {
            var CallReason = new Entities.CallReason
            {
                Description = txtDescription.Text,
                AccounTypeID = int.Parse(ddlProductType.SelectedValue),
                Status = bool.Parse(optOptions.SelectedValue),
            };
            if (!string.IsNullOrEmpty(hfID.Value))
            {
                CallReason.ID = Convert.ToInt32(hfID.Value);
            }
            return CallReason;
        }
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
            Search();
        }
        #endregion

    }
}
